#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include "./network_protocol/include/network.h"
#include "./network_protocol/include/network_common.h"
#include "sample_venc.h"
#include "./uart/serial_uart.h"
#include <math.h>
#include "./network/network_info.h"
#include "conf_time.h"
#include "capture.h"
#include "hh_osd_api.h"
#include "hh_osd.h"

extern CaptureInfo_S state;
// extern NetworkContorlOSDShowState osdShow;
extern NetworkConfigOtherPreview otherPreview;
extern VIDEO_OSD_STATUS *pvideo_osd_status;
HI_OSD_ORG   osd_pos;
OSD_RGBQUAD    osd_color;
HH_OSD_LOGO osd_info;
int init_osd_flag = 0;
// int osd_show_flag = 1;
int cvbs = 1;
int ldc_type = 0;
int ldc_value = 0;
int frame_rate = 50;
char cmd[64];
typedef struct {
    NetworkConfigSystemTimeInfo system_time_info;
    NetworkConfigNetworkNtpInfo network_ntp_info;

    NetworkConfigCameraIrImageInfos camera_ir_image_infos;
    NetworkConfigCameraIrImageEnhances camera_ir_image_enhances;
    NetworkConfigCameraIrImageZooms camera_ir_image_zooms;
    NetworkConfigCameraIrFocusings camera_ir_focusings;
    NetworkConfigCameraIrCalibrations camera_ir_calibrations;
    NetworkConfigCameraIrOsdInfos camera_ir_osd_infos;
    NetworkConfigCameraIrEncodeInfos camera_ir_encode_infos;
	NetworkConfigCameraIrLdcInfos camera_ir_ldc_infos;

    NetworkConfigCameraVisImageInfos camera_vis_image_infos;
    NetworkConfigCameraVisImageZooms camera_vis_image_zooms;
    NetworkConfigCameraVisFocusings camera_vis_focusings;

    NetworkConfigPtzInfo ptz_info;
    NetworkConfigPtzPresets ptz_presets;

    NetworkConfigAlgorithmDetection algorithm_detection;
    NetworkConfigAlgorithmAreas algorithm_areas;
    NetworkConfigAlgorithmImage algorithm_image;

    NetworkConfigNetworkTcpIp network_tcp_ip;

    NetworkConfigDisplayScreenInfo display_screen_info;
    NetworkConfigDisplayScreenCalibrationGun display_screen_calibration_gun;
    NetworkConfigDisplayScreenRedDotInfo display_screen_red_dot_info;

    NetworkConfigOtherInfo other_info;
    NetworkConfigOtherPreview other_preview;
    NetworkConfigOtherPosition other_position;

    NetworkConfigStorageInfo storage_info;
	NetworkConfigStorageRecordProgram storage_record_program;
	NetworkConfigStorageSnapProgram storage_snap_program;
	NetworkConfigStorageSnapParam storage_snap_param;
}Mng;
static Mng kMng;

typedef struct {
    int type;
    void* st;
}NetworkConfigInfo;

static NetworkConfigInfo kNetworkConfigInfo[] = {
    {.type = NETWORK_CONFIG_SYSTEM_TIME_INFO,       .st = &kMng.system_time_info},
    {.type = NETWORK_CONFIG_NETWORK_NTP_INFO, .st = &kMng.network_ntp_info},
    {.type = NETWORK_CONFIG_PTZ_INFO,               .st = &kMng.ptz_info},
    {.type = NETWORK_CONFIG_ALGORITHM_DETECTION,    .st = &kMng.algorithm_detection},
    {.type = NETWORK_CONFIG_ALGORITHM_IMAGE,        .st = &kMng.algorithm_image},
    {.type = NETWORK_CONFIG_NETWORK_TCP_IP,         .st = &kMng.network_tcp_ip},
    {.type = NETWORK_CONFIG_DISPLAY_SCREEN_INFO,    .st = &kMng.display_screen_info},
    {.type = NETWORK_CONFIG_DISPLAY_SCREEN_CALIBRATION_GUN, .st = &kMng.display_screen_calibration_gun},
    {.type = NETWORK_CONFIG_DISPLAY_SCREEN_RED_DOT_INFO, .st = &kMng.display_screen_red_dot_info},
    {.type = NETWORK_CONFIG_OTHER_INFO,             .st = &kMng.other_info},
    {.type = NETWORK_CONFIG_OTHER_PREVIEW,          .st = &kMng.other_preview},
    {.type = NETWORK_CONFIG_OTHER_POSITION,         .st = &kMng.other_position},
    {.type = NETWORK_CONFIG_STORAGE_INFO, .st = &kMng.storage_info},
	{.type = NETWORK_CONFIG_STORAGE_RECORD_PROGRAM, .st = &kMng.storage_record_program},
	{.type = NETWORK_CONFIG_STORAGE_SNAP_PROGRAM, .st = &kMng.storage_snap_program},
	{.type = NETWORK_CONFIG_STORAGE_SNAP_PARAM, .st = &kMng.storage_snap_param},
};

typedef enum {
    TRANSPARENT_TRANSMISSION_PSEUDO_COLOR               = 0xB2,//伪彩
    TRANSPARENT_TRANSMISSION_ELECTRONIC_ZOOM            = 0xD4,//电子变倍
    TRANSPARENT_TRANSMISSION_SHUTTER_CALIBRATION_SWITCH = 0xCF,//快门校正开关
    TRANSPARENT_TRANSMISSION_MANUAL_SHUTTER_CALIBRATION = 0xD0,//手动快门校正
    TRANSPARENT_TRANSMISSION_HORIZONTAL_IMAGE_FLIP      = 0xB8,//图像水平翻转
    TRANSPARENT_TRANSMISSION_VERTICAL_IMAGE_FLIP        = 0xB9,//图像垂直翻转
    TRANSPARENT_TRANSMISSION_ANALOG_VIDEO_SWITCH        = 0xD5,//模拟视频开关
    TRANSPARENT_TRANSMISSION_OUTPUT_VIDEO_FORMAT        = 0xE9,//视频输出格式
    TRANSPARENT_TRANSMISSION_SAVE_USER_CONFIG           = 0xEA,//保存用户配置
    TRANSPARENT_TRANSMISSION_GET_USER_CONFIG            = 0xEB,//获取用户配置
    TRANSPARENT_TRANSMISSION_COMMAND_HEADER             = 0xAA,//命令头
}TransparentTransmissionType;

int GetAbility(NetworkAbilitySupportFunction* func) {
    
    memset(func, 0x0, sizeof(NetworkAbilitySupportFunction));

    // memset((void *)&func->camera_ir_funcs, 0x0, sizeof(NetworkAbilityCameraIrFunctions));
    func->camera_ir_funcs.num = 1;
    func->camera_ir_funcs.camera_ir[0].support_state = 1;
    func->camera_ir_funcs.camera_ir[0].camera_ir_image_info.pseudo_color_support_mask = (1 << 0) | (1 << 1) | (1 << 2) | (0 << 3) | (0 << 4) | (0 << 5) | (0 << 6) | (1 << 8);
    printf("color_mask:%lu\n",func->camera_ir_funcs.camera_ir[0].camera_ir_image_info.pseudo_color_support_mask );
    func->camera_ir_funcs.camera_ir[0].camera_ir_image_info.flip_support = 1;
    func->camera_ir_funcs.camera_ir[0].camera_ir_image_info.mirror_support = 1;
    
    func->camera_ir_funcs.camera_ir[0].camera_ir_calibration.shutter_calibration_support = 1;
    func->camera_ir_funcs.camera_ir[0].camera_ir_image_zoom.electronic_zoom_support = 3;

    // memset((void *)&func->camera_vis_funcs, 0x0, sizeof(NetworkAbilityCameraVisFunctions));
    func->camera_vis_funcs.num = 1;
    // memset((void *)&func->ptz_func, 0x0, sizeof(NetworkAbilityPtzFunction));
    // memset((void *)&func->algorithm_func, 0x0, sizeof(NetworkAbilityAlgorithmFunction));
    // memset((void *)&func->network_func, 0x0, sizeof(NetworkAbilityNetworkFunction));
    // memset((void *)&func->display_screen_func, 0x0, sizeof(NetworkAbilityDisplayScreenFunction)); 
    // memset((void *)&func->other_func, 0x0, sizeof(NetworkAbilityOtherFunction));
    func->other_func.preview.cvbs_support = 1;

    return 0;
}

#define SET_FUNC(st_nm, st, sub, conf, max) \
    do { \
        st_nm* _st = (st_nm*)conf;  \
        if(_st->deal_num == -1) {   \
            memcpy(&kMng.st, _st, sizeof(kMng.st)); \
        } else if (_st->deal_num < max) {   \
            memcpy(&kMng.st.sub[_st->deal_num], &_st->sub[0], sizeof(_st->sub[0])); \
        }   \
    }while(0);

#define GET_FUNC(st_nm, st, sub, n, conf, max) \
    do { \
        st_nm* _st = (st_nm*)conf;  \
        if(_st->deal_num == -1) {   \
            memcpy(_st, &kMng.st, sizeof(kMng.st)); \
        } else if (_st->deal_num < max) {   \
            _st->n = 1; \
            memcpy(&_st->sub[0], &kMng.st.sub[_st->deal_num], sizeof(_st->sub[0])); \
        }   \
    }while(0);

static void *delay_reboot(void* arg){
    sync();//先同步磁盘数据
    stop_recorder_and_save();
    sleep(5);
    printf("exe reboot -f\n");
    system("reboot -f");
    return NULL;
}

int SetConfig(int type, void* conf, int size) {
    printf("func:%s:%d type:%d\n", __func__, __LINE__, type);
    int ret = -1;
    for (int i = 0; i < sizeof(kNetworkConfigInfo)/sizeof(NetworkConfigInfo); i++) {
        if (type == kNetworkConfigInfo[i].type) {
            if(NETWORK_CONFIG_NETWORK_TCP_IP == type){
                NetworkConfigNetworkTcpIp *net_info = (NetworkConfigNetworkTcpIp*)conf;
                printf("net_info->[%s %s %s %s %s %s]\n", net_info->ipv4_enable, net_info->ipv4_addr,net_info->ipv4_mask, net_info->ipv4_gateway, net_info->dns,net_info->mac);
                ret = write_netinfo_to_ini((void*)net_info);

                ret = save_network_config(net_info);
                if(0 == ret)
                {
                    write_rtspurl_to_ini(NULL);
                    // set_network_config("eth0", net_info->ipv4_addr, net_info->ipv4_mask, net_info->ipv4_gateway);
                    //网络信息设置后，需要重启设备
                    modify_yml( net_info->ipv4_addr);
                    
                    printf("Device will be reboot [%d]!!!\n",__LINE__);

                    pthread_t thread_id;
                    if(pthread_create(&thread_id, NULL, delay_reboot, NULL ) != 0){
                        perror("Create delay_reboot pthread failed!\n");
                        return -1;
                    }

                    printf("Device will be reboot [%d]!!!\n",__LINE__);
                }else{
                    printf("rtsp write to conf file failed!\n");
                    return ret;
                }
            }else if(type == NETWORK_CONFIG_OTHER_PREVIEW){
                NetworkConfigOtherPreview *other_preview = (NetworkConfigOtherPreview*)conf;
                printf("other_preview->cvbs=%d\n", other_preview->cvbs);
                otherPreview.cvbs = other_preview->cvbs;
            }else if(type == NETWORK_CONFIG_SYSTEM_TIME_INFO)
            {
                printf("set time\n");
                NetworkConfigSystemTimeInfo *time_info = (NetworkConfigSystemTimeInfo *)conf;
                printf("time_zone:%s,time_format:%d,summer_time:%d, timing_type:%d\n", time_info->time_zone, time_info->time_format, time_info->summer_time, time_info->timing_type);
                save_time_info_to_ini(time_info);
                //设置时区 todo
                // if(time_info->timing_type == 1)
                { //ntp校时才设置时区
                    set_timezone_by_value(time_info->time_zone);
                }
            }else if(type == NETWORK_CONFIG_NETWORK_NTP_INFO){
                NetworkConfigNetworkNtpInfo *ntp_info = (NetworkConfigNetworkNtpInfo *)conf;
                printf("server_addr:%s,ntp_port:%d,time_interval:%d\n", ntp_info->server_addr, ntp_info->port, ntp_info->interval);
                
                ret = set_time_by_ntp(ntp_info);
                if(0 == ret){
                    save_ntp_info_to_ini(ntp_info);
                    rtc_init_systime_to_rtc();
                }
                
                printf("ntp test cmd!\n");
            }else if(type == NETWORK_CONFIG_STORAGE_RECORD_PROGRAM){
                NetworkConfigStorageRecordProgram *record_program = (NetworkConfigStorageRecordProgram *)conf;
                printf("Record_program is ok!\n");
                printf("enable:%d\n",record_program->enable);
                //默认5min中一个录像
                if(record_program->enable){
                    // start_recording();
                    set_recording_enabled(1);
                    
                }else{
                    // stop_recording();
                    set_recording_enabled(0);
                }
                // save_record_program_to_ini(record_program);
            }else if(type == NETWORK_CONFIG_STORAGE_SNAP_PROGRAM){
                NetworkConfigStorageSnapProgram *snap_program = (NetworkConfigStorageSnapProgram *)conf;
                printf("Snap_program is ok!\n");
            }
            else if(type == NETWORK_CONFIG_STORAGE_SNAP_PARAM){
                NetworkConfigStorageSnapParam *snap_info = (NetworkConfigStorageSnapParam *)conf;
                printf("It is ok!\n");
                printf("snap_info->timing_snap_enable:%d\n", snap_info->timing_snap_enable);
                printf("snap_info->timing_snap.interval:%d\n", snap_info->timing_snap.interval);
                printf("snap_info->timing_snap.num:%d\n", snap_info->timing_snap.num);
                printf("snap_info->timing_snap.quality:%d\n", snap_info->timing_snap.quality);
                printf("snap_info->timing_snap.resolution:%d\n", snap_info->timing_snap.resolution);
                printf("snap_info->timing_snap.image_format:%d\n", snap_info->timing_snap.image_format);
                
                save_snap_info_to_ini(snap_info);
                memcpy(&state.CaptureInfo, snap_info, sizeof(NetworkConfigStorageSnapParam));
                // set_capture_flag(&state, snap_info);
                set_capture_config(&state, snap_info);
            }
           
            memcpy(kNetworkConfigInfo[i].st, conf, size);
            return 0;
        }
    }
    
    switch (type)
    {
    case NETWORK_CONFIG_CAMERA_IR_IMAGE_INFO:{
        // SET_FUNC(NetworkConfigCameraIrImageInfos, camera_ir_image_infos, image_info, conf, NETWORK_CAMERA_MAX_NUM);
        NetworkCameraChipInfo get_chip_ctrl;
        load_camera_chip_config(&get_chip_ctrl);
        printf("-----[%d]--->[%d %f %d %d]\n",__LINE__,get_chip_ctrl.pseudo_color, get_chip_ctrl.electronic_zoom, get_chip_ctrl.horizontal_image_flip, get_chip_ctrl.vertical_image_flip);
        do { 
            NetworkConfigCameraIrImageInfos* _st = (NetworkConfigCameraIrImageInfos*)conf; 
            printf("chip_ctrl pseudo_color->[_st->%d  kMng->%d]\n", _st->image_info[0].pseudo_color, kMng.camera_ir_image_infos.image_info[0].pseudo_color);
            if(_st->image_info[0].pseudo_color != kMng.camera_ir_image_infos.image_info[0].pseudo_color  && _st->image_info[0].pseudo_color >=0 && _st->image_info[0].pseudo_color <= 2 || 8 == _st->image_info[0].pseudo_color )//只实现了极性控制
            {
                get_chip_ctrl.pseudo_color = _st->image_info[0].pseudo_color;
                ret = chip_ctrl_init(DEVICE , CHIP_CRTL_PSEUDO_COLOR, &get_chip_ctrl); 
                if(0 != ret){
                    printf("set PSEUDO_COLOR failed!\n");
                    return ret;
                }
            }

            printf("mirror:%d, flip:%d\n", _st->image_info[0].mirror, _st->image_info[0].flip);
            if( _st->image_info[0].mirror !=  kMng.camera_ir_image_infos.image_info[0].mirror){
                get_chip_ctrl.horizontal_image_flip = _st->image_info[0].mirror;
                ret = chip_ctrl_init(DEVICE, CHIP_CRTL_HORIZONTAL_IMAGE_FLIP, &get_chip_ctrl);
                if(0 != ret){
                    printf("set CHIP_CRTL_HORIZONTAL_IMAGE_FLIP failed!\n");
                    return ret;
                }
            }

            if( _st->image_info[0].flip != kMng.camera_ir_image_infos.image_info[0].flip){
                get_chip_ctrl.vertical_image_flip = _st->image_info[0].flip;
                ret = chip_ctrl_init(DEVICE, CHIP_CRTL_VERTICAL_IMAGE_FLIP, &get_chip_ctrl);
                if(0 != ret){
                    printf("set CHIP_CRTL_HORIZONTAL_IMAGE_FLIP failed!\n");
                    return ret;
                }
            }
            
            if(_st->deal_num == -1) { 
                memcpy(&kMng.camera_ir_image_infos, _st, sizeof(kMng.camera_ir_image_infos)); 
            } else if (_st->deal_num < (4)) { 
                memcpy(&kMng.camera_ir_image_infos.image_info[_st->deal_num], &_st->image_info[0], sizeof(_st->image_info[0])); 
            } 
            // write_chipctrl_to_ini((void *)&get_chip_ctrl);
            save_camera_chip_config(&get_chip_ctrl);
        }while(0);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_IMAGE_ENHANCE:{
        SET_FUNC(NetworkConfigCameraIrImageEnhances, camera_ir_image_enhances, image_enhance, conf, NETWORK_CAMERA_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_IMAGE_ZOOM:{
        // SET_FUNC(NetworkConfigCameraIrImageZooms, camera_ir_image_zooms, image_zoom, conf, NETWORK_CAMERA_MAX_NUM);
        do { 
            NetworkCameraChipInfo get_chip_ctrl;
            load_camera_chip_config(&get_chip_ctrl);
            NetworkConfigCameraIrImageZooms* _st = (NetworkConfigCameraIrImageZooms*)conf; 
            // printf("chip_ctrl electronic_zoom ->[_st->%.2f kMng->%.2f]\n",_st->image_zoom[0].electronic,kMng.camera_ir_image_zooms.image_zoom[0].electronic);
            float epsilon = 1e-5f;
            if(!(fabs(_st->image_zoom[0].electronic - kMng.camera_ir_image_zooms.image_zoom[0].electronic) < epsilon))
            {
                get_chip_ctrl.electronic_zoom = _st->image_zoom[0].electronic;
                ret = chip_ctrl_init(DEVICE , CHIP_CRTL_ELECTRONIC_ZOOM, &get_chip_ctrl);
                if(0 != ret){
                    printf("set ELECTRONIC_ZOOM failed!\n");
                    return ret;
                }
            }

            if(_st->deal_num == -1) { 
                memcpy(&kMng.camera_ir_image_zooms, _st, sizeof(kMng.camera_ir_image_zooms)); 
            } else if (_st->deal_num < (4)) { 
                memcpy(&kMng.camera_ir_image_zooms.image_zoom[_st->deal_num], &_st->image_zoom[0], sizeof(_st->image_zoom[0])); 
            } 
            // write_chipctrl_to_ini((void *)&get_chip_ctrl);
            printf("chip_ctrl electronic_zoom ->[electronic_zoom->%.2f]\n",get_chip_ctrl.electronic_zoom);
            save_camera_chip_config(&get_chip_ctrl);
        }while(0);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_FOCUSING:{
        SET_FUNC(NetworkConfigCameraIrFocusings, camera_ir_focusings, focusing, conf, NETWORK_CAMERA_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_CALIBRATIONS:{
        // SET_FUNC(NetworkConfigCameraIrCalibrations, camera_ir_calibrations, calibration, conf, NETWORK_CAMERA_MAX_NUM);
        do { 
            NetworkCameraChipInfo get_chip_ctrl;
            load_camera_chip_config(&get_chip_ctrl);
            NetworkConfigCameraIrCalibrations* _st = (NetworkConfigCameraIrCalibrations*)conf; 
            printf("chip_ctrl shutter ->[_st->%d kMng->%d]\n",_st->calibration[0].shutter,kMng.camera_ir_calibrations.calibration[0].shutter);
            if(_st->calibration[0].shutter != get_chip_ctrl.shutter_calibration)
            {
                get_chip_ctrl.shutter_calibration = _st->calibration[0].shutter;
                ret = chip_ctrl_init(DEVICE , CHIP_CRTL_SHUTTER_CALIBRATION, &get_chip_ctrl);
                if(0 != ret){
                    printf("set SHUTTER_CALIBRATION failed!\n");
                    return ret;
                }
            }
            
            if(_st->deal_num == -1) { 
                memcpy(&kMng.camera_ir_calibrations, _st, sizeof(kMng.camera_ir_calibrations)); 
            } else if (_st->deal_num < (4)) { 
                memcpy(&kMng.camera_ir_calibrations.calibration[_st->deal_num], &_st->calibration[0], sizeof(_st->calibration[0])); 
            } 
            // write_chipctrl_to_ini((void *)&get_chip_ctrl);
            save_camera_chip_config(&get_chip_ctrl);
        }while(0);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_OSD_INFO:{
        // SET_FUNC(NetworkConfigCameraIrOsdInfos, camera_ir_osd_infos, osd_info, conf, NETWORK_CAMERA_MAX_NUM);
        do { 
            NetworkConfigCameraIrOsdInfos* _st = (NetworkConfigCameraIrOsdInfos*)conf; 
            NetworkConfigOsdInfo read_info = {0};
            load_osd_info_from_ini(&read_info);

            printf("_st->deal_num:%d, _st->num:%d, camera_name:%s, 0.value;%s\n", _st->deal_num,  _st->num,  _st->osd_info->camera_name,_st->osd_info->string_overlay[0].value );
            if(_st->deal_num == -1) 
            { 
                memcpy(&kMng.camera_ir_osd_infos, _st, sizeof(kMng.camera_ir_osd_infos)); 
                memcpy(&read_info, &_st->osd_info[0], sizeof(read_info));
            } else if (_st->deal_num < (4)) 
            { 
                memcpy(&kMng.camera_ir_osd_infos.osd_info[_st->deal_num], &_st->osd_info[0], sizeof(_st->osd_info[0])); 
                memcpy(&read_info,  &_st->osd_info[0], sizeof(_st->osd_info[0]));
            } 

            set_osd_info(&read_info);
            save_osd_info_to_ini(&read_info);
        }while(0);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_ENCODE_INFO:{
        NetworkConfigCameraIrEncodeInfos* encode_info = (NetworkConfigCameraIrEncodeInfos*)conf;
        printf("fps=%d\n", encode_info->encode_info[0][0].fps);
        frame_rate = encode_info->encode_info[0][0].fps;
		if (encode_info->deal_cam != -1 && encode_info->deal_stream != -1) {
			memcpy(&kMng.camera_ir_encode_infos.encode_info[encode_info->deal_cam][encode_info->deal_stream], &encode_info->encode_info[0][0], sizeof(NetworkConfigCameraIrEncodeInfo));
		} else {
			memcpy(&kMng.camera_ir_encode_infos, encode_info, sizeof(NetworkConfigCameraIrEncodeInfos));
		}
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_LDC_INFO:{

        // SET_FUNC(NetworkConfigCameraIrLdcInfos, camera_ir_ldc_infos, ldc, deal_cam, conf, NETWORK_CAMERA_MAX_NUM);
        do { 
            NetworkConfigCameraIrLdcInfos* _st = (NetworkConfigCameraIrLdcInfos*)conf; 
            printf("_st->cam_num:%d, _st->deal_cam:%d, _st->ldc[0].enable:%d, \
                _st->ldc[0].view_type;%d,_st->ldc[0].center_offset.x;%d, _st->ldc[0].center_offset.y:%d \
                _st->ldc[0].distortion_ratio:%d, _st->ldc[0].min_distortion_ratio:%d\n",
                 _st->cam_num, _st->deal_cam, 
                _st->ldc[0].enable, _st->ldc[0].view_type,
                _st->ldc[0].center_offset.x,_st->ldc[0].center_offset.y,
                _st->ldc[0].distortion_ratio,
                _st->ldc[0].min_distortion_ratio
            );
            {
                memset(cmd, 0 , sizeof(cmd));
                sprintf(cmd, "./sample_vo 0 %d", _st->ldc[0].view_type);
                system(cmd);
                memset(cmd, 0 , sizeof(cmd));
                sprintf(cmd, "./sample_vo 1 %d", _st->ldc[0].center_offset.x);
                system(cmd);
                memset(cmd, 0 , sizeof(cmd));
                sprintf(cmd, "./sample_vo 2 %d", _st->ldc[0].center_offset.y);
                system(cmd);
                memset(cmd, 0 , sizeof(cmd));
                sprintf(cmd, "./sample_vo 3 %d", _st->ldc[0].distortion_ratio);
                system(cmd);
                memset(cmd, 0 , sizeof(cmd));
                sprintf(cmd, "./sample_vo 4 %d", _st->ldc[0].min_distortion_ratio);
                system(cmd);
                memset(cmd, 0 , sizeof(cmd));
                sprintf(cmd, "./sample_vo 5 %d", _st->ldc[0].enable);
                system(cmd);
            }
            if(_st->deal_cam == -1) { 
                memcpy(&kMng.camera_ir_ldc_infos, _st, sizeof(NetworkConfigCameraIrLdcInfos)); 
            } else if (_st->deal_cam < (4)) { 
                memcpy(&kMng.camera_ir_ldc_infos.ldc[_st->deal_cam], &_st->ldc[0], sizeof(NetworkConfigCameraIrLdcInfos)); 
            } 
        }while(0);

        break;
    }
    case NETWORK_CONFIG_CAMERA_VIS_IMAGE_INFO:{
        SET_FUNC(NetworkConfigCameraVisImageInfos, camera_vis_image_infos, image_info, conf, NETWORK_CAMERA_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_CAMERA_VIS_IMAGE_ZOOM:{
        SET_FUNC(NetworkConfigCameraVisImageZooms, camera_vis_image_zooms, image_zoom, conf, NETWORK_CAMERA_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_CAMERA_VIS_FOCUSING:{
        SET_FUNC(NetworkConfigCameraVisFocusings, camera_vis_focusings, focusing, conf, NETWORK_CAMERA_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_PTZ_PRESETS:{
        SET_FUNC(NetworkConfigPtzPresets, ptz_presets, preset, conf, NETWORK_CONFIG_PRESET_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_ALGORITHM_AREAS:{
        SET_FUNC(NetworkConfigAlgorithmAreas, algorithm_areas, area, conf, NETWORK_CONFIG_AREA_NUM_MAX);
        break;
    }
    default:
        break;
    }

    return 0;
}

int GetConfig(int type, void* conf, int size) {
    printf("func:%s:%d type:%d\n", __func__, __LINE__, type);
    for (int i = 0; i < sizeof(kNetworkConfigInfo)/sizeof(NetworkConfigInfo); i++) {
        if (type == kNetworkConfigInfo[i].type) {
            if(type == NETWORK_CONFIG_NETWORK_TCP_IP)
            {
                get_netinfo_from_ini(kNetworkConfigInfo[i].st);
            }else if(type == NETWORK_CONFIG_SYSTEM_TIME_INFO){
              
                NetworkConfigSystemTimeInfo time_info;
                memset(&time_info, 0x0, sizeof(time_info));
                load_time_info_from_ini(&time_info);
                printf("get_time time_info.time_zone:%s, time_info.time_format:%d, time_info.summer_time:%d, time_info.timing_type:%d\n",time_info.time_zone, time_info.time_format, time_info.summer_time, time_info.timing_type );
                memcpy(kNetworkConfigInfo[i].st, &time_info, sizeof(time_info));

            }else if(type == NETWORK_CONFIG_NETWORK_NTP_INFO){
               
                NetworkConfigNetworkNtpInfo ntp_info;
                memset(&ntp_info, 0x0, sizeof(ntp_info));
                load_ntp_info_from_ini(&ntp_info);
                printf("get_ntp ntp_info.server_addr:%s, tntp_info.ntp_port:%d, ntp_info.time_interval:%d\n",ntp_info.server_addr, ntp_info.port, ntp_info.interval );
                memcpy(kNetworkConfigInfo[i].st, &ntp_info, sizeof(ntp_info));
            }else if(type == NETWORK_CONFIG_STORAGE_RECORD_PROGRAM){
                printf("NETWORK_CONFIG_STORAGE_RECORD_PROGRAM get ok!\n");
            }else if(type == NETWORK_CONFIG_STORAGE_SNAP_PROGRAM){
                printf("NETWORK_CONFIG_STORAGE_SNAP_PROGRAM get ok!\n");
            }else if(type == NETWORK_CONFIG_STORAGE_SNAP_PARAM){
                printf("NETWORK_CONFIG_STORAGE_SNAP_PARAM get ok!\n");
                NetworkConfigStorageSnapParam snap_info ;
                memset(&snap_info, 0x0, sizeof(snap_info));
                load_snap_info_from_ini(&snap_info);
                printf("snap_info->timing_snap_enable:%d\n", snap_info.timing_snap_enable);
                printf("snap_info->timing_snap.interval:%d\n", snap_info.timing_snap.interval);
                printf("snap_info->timing_snap.num:%d\n", snap_info.timing_snap.num);
                printf("snap_info->timing_snap.quality:%d\n", snap_info.timing_snap.quality);
                printf("snap_info->timing_snap.resolution:%d\n", snap_info.timing_snap.resolution);
                printf("snap_info->timing_snap.image_format:%d\n", snap_info.timing_snap.image_format);

                memcpy(kNetworkConfigInfo[i].st, &snap_info, sizeof(snap_info));
            }

            memcpy(conf, kNetworkConfigInfo[i].st, size);

            return 0;
        }
    }
    
    switch (type)
    {
    case NETWORK_CONFIG_CAMERA_IR_IMAGE_INFO:{
        // GET_FUNC(NetworkConfigCameraIrImageInfos, camera_ir_image_infos, image_info, num, conf, NETWORK_CAMERA_MAX_NUM);
        do { 
            NetworkCameraChipInfo chip_ctrl;
            load_camera_chip_config(&chip_ctrl);
            // get_chipctrl_from_ini(&chip_ctrl);
            NetworkConfigCameraIrImageInfos* _st = (NetworkConfigCameraIrImageInfos*)conf; 
            printf("_st->deal_num=%d\n",_st->deal_num);

            if(_st->deal_num == -1) {
                kMng.camera_ir_image_infos.num = 1;
                kMng.camera_ir_image_infos.image_info[0].pseudo_color = chip_ctrl.pseudo_color;
                kMng.camera_ir_image_infos.image_info[0].mirror = chip_ctrl.horizontal_image_flip;
                kMng.camera_ir_image_infos.image_info[0].flip   = chip_ctrl.vertical_image_flip;

                memcpy(_st, &kMng.camera_ir_image_infos, sizeof(kMng.camera_ir_image_infos)); 
                // _st->image_info[0].pseudo_color = chip_ctrl.pseudo_color;
            } else if (_st->deal_num < (4)) { 
                _st->num = 1; 
                kMng.camera_ir_image_infos.image_info[_st->deal_num].pseudo_color = chip_ctrl.pseudo_color;
                kMng.camera_ir_image_infos.image_info[_st->deal_num].mirror = chip_ctrl.horizontal_image_flip;
                kMng.camera_ir_image_infos.image_info[_st->deal_num].flip   = chip_ctrl.vertical_image_flip;

                memcpy(&_st->image_info[0], &kMng.camera_ir_image_infos.image_info[_st->deal_num], sizeof(_st->image_info[0])); 
                // _st->image_info[0].pseudo_color = chip_ctrl.pseudo_color;
            } 

            // printf("_st->deal_num=%d,%d\n",_st->deal_num, _st->image_info[0].pseudo_color);
        }while(0);

        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_IMAGE_ENHANCE:{
        GET_FUNC(NetworkConfigCameraIrImageEnhances, camera_ir_image_enhances, image_enhance, num, conf, NETWORK_CAMERA_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_IMAGE_ZOOM:{
        // GET_FUNC(NetworkConfigCameraIrImageZooms, camera_ir_image_zooms, image_zoom, num, conf, NETWORK_CAMERA_MAX_NUM);
        do { 
            NetworkCameraChipInfo chip_ctrl;        
            load_camera_chip_config(&chip_ctrl);
            NetworkConfigCameraIrImageZooms* _st = (NetworkConfigCameraIrImageZooms*)conf; 
            // printf("_st->deal_num=%d, chip_ctrl.electronic_zoom:%f\n",_st->deal_num, chip_ctrl.electronic_zoom);
            if(_st->deal_num == -1) { 
                kMng.camera_ir_image_zooms.num = 1;
                kMng.camera_ir_image_zooms.image_zoom[0].electronic = chip_ctrl.electronic_zoom;
                memcpy(_st, &kMng.camera_ir_image_zooms, sizeof(kMng.camera_ir_image_zooms)); 
                // _st->image_zoom[0].electronic = chip_ctrl.electronic_zoom;
            } else if (_st->deal_num < (4)) { 
                _st->num = 1; 
                memcpy(&_st->image_zoom[0], &kMng.camera_ir_image_zooms.image_zoom[_st->deal_num], sizeof(_st->image_zoom[0])); 
                _st->image_zoom[0].electronic = chip_ctrl.electronic_zoom;
            } 

            // printf("_st->deal_num=%d,%0.2f\n",_st->deal_num,_st->image_zoom[0].electronic);
        }while(0);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_FOCUSING:{
        GET_FUNC(NetworkConfigCameraIrFocusings, camera_ir_focusings, focusing, num, conf, NETWORK_CAMERA_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_CALIBRATIONS:{
        // GET_FUNC(NetworkConfigCameraIrCalibrations, camera_ir_calibrations, calibration, num, conf, NETWORK_CAMERA_MAX_NUM);
        do { 
            NetworkCameraChipInfo chip_ctrl;
           
            load_camera_chip_config(&chip_ctrl);
            NetworkConfigCameraIrCalibrations* _st = (NetworkConfigCameraIrCalibrations*)conf; 
            printf("_st->deal_num=%d\n",_st->deal_num);
            if(_st->deal_num == -1) {
                kMng.camera_ir_calibrations.num = 1;
                kMng.camera_ir_calibrations.calibration[0].shutter = chip_ctrl.shutter_calibration;
                memcpy(_st, &kMng.camera_ir_calibrations, sizeof(kMng.camera_ir_calibrations)); 
                // _st->calibration[0].shutter = chip_ctrl.shutter_calibration;
            } else if (_st->deal_num < (4)) { 
                _st->num = 1; 
                memcpy(&_st->calibration[0], &kMng.camera_ir_calibrations.calibration[_st->deal_num], sizeof(_st->calibration[0])); 
                _st->calibration[0].shutter = chip_ctrl.shutter_calibration;
            } 

            printf("_st->deal_num=%d,%d\n",_st->deal_num,_st->calibration[0].shutter);
        }while(0);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_OSD_INFO:{
        // GET_FUNC(NetworkConfigCameraIrOsdInfos, camera_ir_osd_infos, osd_info, num, conf, NETWORK_CAMERA_MAX_NUM);
        do { 
            NetworkConfigCameraIrOsdInfos* _st = (NetworkConfigCameraIrOsdInfos*)conf; 
            printf("_st->deal_num:%d, _st->num:%d, camera_name:%s, 0.value;%s\n", _st->deal_num,  _st->num,  _st->osd_info->camera_name,_st->osd_info->string_overlay[0].value );
            NetworkConfigOsdInfo read_info = {0};
            load_osd_info_from_ini(&read_info);

            if(_st->deal_num == -1) 
            { 
                memcpy(_st, &kMng.camera_ir_osd_infos, sizeof(kMng.camera_ir_osd_infos));
                memcpy(&_st->osd_info[0], &read_info, sizeof(read_info));
            } else if (_st->deal_num < (4)) 
            { 
                _st->num = 1; 
                memcpy(&_st->osd_info[0], &kMng.camera_ir_osd_infos.osd_info[_st->deal_num], sizeof(_st->osd_info[0])); 
                memcpy(&_st->osd_info[0], &read_info, sizeof(read_info));
            } 

            
        }while(0);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_ENCODE_INFO:{
		NetworkConfigCameraIrEncodeInfos* encode_info = (NetworkConfigCameraIrEncodeInfos*)conf;
		
		if (encode_info->deal_cam != -1 && encode_info->deal_stream != -1) {
			encode_info->cam_num = 1;
			encode_info->stream_num[0] = 1;
			memcpy(&encode_info->encode_info[0][0], &kMng.camera_ir_encode_infos.encode_info[encode_info->deal_cam][encode_info->deal_stream], sizeof(NetworkConfigCameraIrEncodeInfo));
		} else {
			encode_info->cam_num = kMng.camera_ir_encode_infos.cam_num;
			memcpy(encode_info->stream_num, kMng.camera_ir_encode_infos.stream_num, sizeof(kMng.camera_ir_encode_infos.stream_num));
			memcpy(encode_info->encode_info, kMng.camera_ir_encode_infos.encode_info, sizeof(encode_info->encode_info));
		}
        printf("deal_cam:%d, deal_stream:%d,encode_info[0][0].fps=%d\n", encode_info->deal_cam, encode_info->deal_stream, encode_info->encode_info[0][0].fps);
        break;
    }
    case NETWORK_CONFIG_CAMERA_IR_LDC_INFO:{
        // GET_FUNC(NetworkConfigCameraIrLdcInfos, camera_ir_ldc_infos, ldc, deal_cam, cam_num, conf, NETWORK_CAMERA_MAX_NUM);
        do { 
            NetworkConfigCameraIrLdcInfos* _st = (NetworkConfigCameraIrLdcInfos*)conf; 
            printf("_st->cam_num:%d, _st->deal_cam:%d, _st->ldc[0].enable:%d, \
                _st->ldc[0].view_type;%d,_st->ldc[0].center_offset.x;%d, _st->ldc[0].center_offset.y:%d \
                _st->ldc[0].distortion_ratio:%d, _st->ldc[0].min_distortion_ratio:%d\n",
                 _st->cam_num, _st->deal_cam, 
                _st->ldc[0].enable, _st->ldc[0].view_type,
                _st->ldc[0].center_offset.x,_st->ldc[0].center_offset.y,
                _st->ldc[0].distortion_ratio,
                _st->ldc[0].min_distortion_ratio
            );
           
            if(_st->deal_cam == -1) 
            { 
                memcpy(_st, &kMng.camera_ir_ldc_infos, sizeof(kMng.camera_ir_ldc_infos));
                memcpy(&_st->ldc, &kMng.camera_ir_ldc_infos.ldc, sizeof(NetworkConfigCameraIrLdcInfo));
            } else if (_st->deal_cam < (4)) 
            { 
                _st->cam_num = 1; 
                memcpy(&_st->ldc[0], &kMng.camera_ir_ldc_infos.ldc[_st->deal_cam], sizeof(_st->ldc[0])); 
                // memcpy(&_st->osd_info[0], &read_info, sizeof(read_info));
            } 
        }while(0);
        break;
    }
    case NETWORK_CONFIG_CAMERA_VIS_IMAGE_INFO:{
        GET_FUNC(NetworkConfigCameraVisImageInfos, camera_vis_image_infos, image_info, num, conf, NETWORK_CAMERA_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_CAMERA_VIS_IMAGE_ZOOM:{
        GET_FUNC(NetworkConfigCameraVisImageZooms, camera_vis_image_zooms, image_zoom, num, conf, NETWORK_CAMERA_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_CAMERA_VIS_FOCUSING:{
        GET_FUNC(NetworkConfigCameraVisFocusings, camera_vis_focusings, focusing, num, conf, NETWORK_CAMERA_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_PTZ_PRESETS:{
        GET_FUNC(NetworkConfigPtzPresets, ptz_presets, preset, preset_num, conf, NETWORK_CONFIG_PRESET_MAX_NUM);
        break;
    }
    case NETWORK_CONFIG_ALGORITHM_AREAS:{
        GET_FUNC(NetworkConfigAlgorithmAreas, algorithm_areas, area, area_num, conf, NETWORK_CONFIG_AREA_NUM_MAX);
        break;
    }
    default:
        break;
    }
    
    return 0;
}

int ControlRequest(int type, int cam, void* st, int size) {
    printf("control request type:%d cam:%d\n", type, cam);
    if (type == NETWORK_CONTORL_BAD_PIX && ((NetworkContorlBadPix*)st)->oper == NETWORK_CONTORL_BAD_PIX_OPERATION_GET) {
        ((NetworkContorlBadPix*)st)->pix_num = 123;
    } else if (type == NETWORK_CONTORL_LASER_RANGING && ((NetworkContorlLaserRanging*)st)->mode == NETWORK_CONTORL_LASER_RANGING_SINGLE) {
        ((NetworkContorlLaserRanging*)st)->distence = 12345;
    } else if (type == NETWORK_CONTORL_PTZ) {
        printf("ptz ctrl mode :%d\n", ((NetworkContorlPtzCtrl*)st)->mode);
    } else if (type == NETWORK_CONTORL_IR_FOCUSING) {
        printf("ir focusing mode :%d\n", ((NetworkContorlIrFocusing*)st)->mode);
    }else if(type == NETWORK_CONTORL_SHUTTER_CALIBRATION){
        int ret = chip_ctrl_init(DEVICE , CHIP_CRTL_MANUAL_SHUTTER_CALIBRATION, NULL);
        if(0 != ret){
            printf("set MANUAL_SHUTTER_CALIBRATION failed!\n");
            return ret;
        }
        printf("chip_ctrl_init CHIP_CRTL_MANUAL_SHUTTER_CALIBRATION!!\n");
    }
    else if (type == NETWORK_CONTORL_FILE_OPERATION) {
		if (((NetworkContorlFileOperation*)st)->mode == NETWORK_CONTORL_FILE_OPERATION_QUERY) {
			NetworkContorlFileOperation* _st = (NetworkContorlFileOperation*)st;
            
            printf("file type:%d, mode:%d\n", _st->type,_st->mode);
            printf("file cur_page:%d, sort:%d, start_time:%d, end_time:%d\n", ((NetworkContorlFileOperation*)st)->file_query.page,\
            ((NetworkContorlFileOperation*)st)->file_query.sort,\
            ((NetworkContorlFileOperation*)st)->file_query.start_time,\
            ((NetworkContorlFileOperation*)st)->file_query.end_time);

            if(_st->type == NETWORK_CONTORL_FILE_OPERATION_IMAGE){
                
                NetworkContorlFileOperationQuery params;
                params.page = _st->file_query.page;                 // 请求第 1 页
                params.sort = _st->file_query.sort;  // 按时间升序
                params.start_time = _st->file_query.start_time;           // 所有时间
                params.end_time = _st->file_query.end_time; // 当前时间

                NetworkContorlFileInfos result;

                printf("Querying page %d, sort %d, time [%d, %d]\n",
                    params.page, params.sort, params.start_time, params.end_time);

                if (query_images(&params, &result, 0) == 0) {
                    printf("Query successful.\n");
                    printf("Total matching files: %d\n", result.file_num);
                    printf("Total pages: %d\n", result.page_num);
                    printf("Current page: %d\n", result.cur_page);
                    printf("Files on this page: %d\n", result.num);

                    memcpy(&(_st->file_infos), &result, sizeof(result));
                    for (int i = 0; i < result.num; i++) {
                        printf("File %d: %s, size: %lld\n", i, result.info[i].filename, result.info[i].size);
                    }
                }
            } else{
                printf("record\n");
                _st->file_infos.file_num = 2;
                _st->file_infos.page_num = 1;
                _st->file_infos.cur_page = 1;
                _st->file_infos.num = 2;
                snprintf(_st->file_infos.info[0].filename, sizeof(_st->file_infos.info[0].filename), "file_0.mp4");
                _st->file_infos.info[0].size = 11212;
                snprintf(_st->file_infos.info[1].filename, sizeof(_st->file_infos.info[1].filename), "file_1.mp4");
                _st->file_infos.info[1].size = 11221;

                NetworkContorlFileOperationQuery params;
                params.page = _st->file_query.page;                 // 请求第 1 页
                params.sort = _st->file_query.sort;  // 按时间升序
                params.start_time = _st->file_query.start_time;           // 所有时间
                params.end_time = _st->file_query.end_time; // 当前时间

                NetworkContorlFileInfos result;

                printf("Querying page %d, sort %d, time [%d, %d]\n",
                    params.page, params.sort, params.start_time, params.end_time);

                if (query_images(&params, &result, 1) == 0) {
                    printf("Query successful.\n");
                    printf("Total matching files: %d\n", result.file_num);
                    printf("Total pages: %d\n", result.page_num);
                    printf("Current page: %d\n", result.cur_page);
                    printf("Files on this page: %d\n", result.num);

                    memcpy(&(_st->file_infos), &result, sizeof(result));
                    for (int i = 0; i < result.num; i++) {
                        printf("File %d: %s, size: %lld\n", i, result.info[i].filename, result.info[i].size);
                    }
                }

            }
		} else if (((NetworkContorlFileOperation*)st)->mode == NETWORK_CONTORL_FILE_OPERATION_MODIFY){
			printf("old:%s, new:%s\n", ((NetworkContorlFileOperation*)st)->file_modify.old_filename, ((NetworkContorlFileOperation*)st)->file_modify.new_filename);
		} else {
			printf("filename:%s\n", ((NetworkContorlFileOperation*)st)->file_delete.filename); 
		}
	}
    else if(type == NETWORK_CONTORL_SNAP){
        // CaptureState state;
        // set_capture_flag(&state, 1);

        printf("capture_flag=%d",state.CaptureInfo.timing_snap_enable);
    }else if(type == NETWORK_CONTORL_TELNET){
        NetworkContorlTelnet* telnet_info = (NetworkContorlTelnet*)st;
        printf("telnet enable:%d\n", telnet_info->enable);
        if(telnet_info->enable == 1) {
            printf("start telnet\n");
            system("telnet");
        }
        
    }
    // else if(type == NETWORK_CONTORL_OSD_SHOW)
    // {
    //     // NetworkContorlOSDShowState *osd_show = (NetworkContorlOSDShowState *)st;
    //     // printf("osd_show_state=%d\n",osd_show->osd_state );
    //     // osdShow.osd_state = osd_show->osd_state;
    // }
    return 0;
}

int Upgrade(NetworkUpgradeInfo* info) {

	printf("path:%s, size:%lld, md5:%s, type:%d\n", info->path, info->size, info->md5, info->type);
   
    if(info->type == NETWORK_UPGRADE_CAMERA){
        NetworkCameraChipInfo chip_ctrl; 
        // ，【升级中："upgrading"】【升级成功："upgrade success"】【升级失败："upgrade fail"】
        NetworkUpload upload_info;
        memset(&chip_ctrl, 0x0, sizeof(chip_ctrl));
        memset(&upload_info, 0x0, sizeof(upload_info));
        memcpy(&chip_ctrl.upgrade_chip_path, info->path, sizeof(chip_ctrl.upgrade_chip_path.filename));

        upload_info.type = NETWORK_UPLOAD_UPGRADE;
        memcpy(upload_info.data.upgrade_state, "upgrading", sizeof(upload_info.data.upgrade_state));
        NetworkUploadInfo(&upload_info);

        int ret = 0;
        // chip_ctrl_init(DEVICE, TEST_UPGRADE, &chip_ctrl);
        if(0 > ret){
            printf("chip upgrade failed!,send upgrade fail\n");
            upload_info.type = NETWORK_UPLOAD_UPGRADE;
            memcpy(upload_info.data.upgrade_state, "upgrade fail", sizeof(upload_info.data.upgrade_state));
            NetworkUploadInfo(&upload_info);
        }else{
            upload_info.type = NETWORK_UPLOAD_UPGRADE;
            memcpy(upload_info.data.upgrade_state, "upgrade success", sizeof(upload_info.data.upgrade_state));
            NetworkUploadInfo(&upload_info);
            printf("chip upgrade success!,send upgrade success\n");
        }

        if (remove(info->path) == 0) {
            printf("文件删除成功: %s\n", info->path);
        } else {
            perror("文件删除失败");
        }
    }

    return 0;
}

static int device_init(NetworkCameraChipInfo *get_chip_ctrl);

int TransparentTransmission(NetworkTransparentTransmission* ts) {
    printf("ts type:%s %s", ts->type, ts->in);
  
    int ret = -1;
   if(strcmp(ts->type,  "WEB_CHIP_CONTROL") == 0){
        unsigned char output[32]; // 假设输出缓冲区大小为32
        int max_output_size = sizeof(output) / sizeof(output[0]);

        int parsed_length = parse_hex_string(ts->in, output, max_output_size);
        if (parsed_length <= 0) {
            printf("解析失败\n");
            return -1;
        }

        NetworkCameraChipInfo chip_ctrl; 
        memset(&chip_ctrl, 0x0, sizeof(chip_ctrl));
        if(output[0] == TRANSPARENT_TRANSMISSION_COMMAND_HEADER){
            if(output[1] == TRANSPARENT_TRANSMISSION_HORIZONTAL_IMAGE_FLIP)
            {
                chip_ctrl.horizontal_image_flip = output[2];
                ret = chip_ctrl_init(DEVICE, CHIP_CRTL_HORIZONTAL_IMAGE_FLIP, &chip_ctrl);
            }else if(output[1] == TRANSPARENT_TRANSMISSION_VERTICAL_IMAGE_FLIP){
                chip_ctrl.vertical_image_flip = output[2];
                ret = chip_ctrl_init(DEVICE, CHIP_CRTL_VERTICAL_IMAGE_FLIP, &chip_ctrl);
            }else if(output[1] == TRANSPARENT_TRANSMISSION_ANALOG_VIDEO_SWITCH){
                chip_ctrl.analog_video_switch = output[2];
                ret = chip_ctrl_init(DEVICE, CHIP_CRTL_ANALOG_VIDEO_SWITCH, &chip_ctrl);
            }else if(output[1] == TRANSPARENT_TRANSMISSION_OUTPUT_VIDEO_FORMAT){
                chip_ctrl.output_video_format = output[2];
                ret = chip_ctrl_init(DEVICE, CHIP_CRTL_OUTPUT_VIDEO_FORMAT, &chip_ctrl);
            }else if(output[1] == TRANSPARENT_TRANSMISSION_SAVE_USER_CONFIG){
                ret = chip_ctrl_init(DEVICE, CHIP_CRTL_SAVE_USER_CONFIG, NULL);
            }else if(output[1] == TRANSPARENT_TRANSMISSION_GET_USER_CONFIG){
                chip_ctrl.get_user_config.size = sizeof(chip_ctrl.get_user_config.user_data);
                ret = chip_ctrl_init(DEVICE, CHIP_CRTL_GET_USER_CONFIG, &chip_ctrl);
            }
        }
        
        // printf("发送命令: ");
        // for (int i = 0; i < parsed_length; i++) {
        //     printf("0x%02X ", output[i]);
        // }
        // printf("\n");

        snprintf(ts->out, 1024, "%02x%02x%02x%02x%02x%02x%02x%02x",chip_ctrl.get_user_config.user_data[0],chip_ctrl.get_user_config.user_data[1], 
        chip_ctrl.get_user_config.user_data[2],chip_ctrl.get_user_config.user_data[3],chip_ctrl.get_user_config.user_data[4],chip_ctrl.get_user_config.user_data[5],
        chip_ctrl.get_user_config.user_data[6],chip_ctrl.get_user_config.user_data[7]);
        // ,chip_ctrl.get_user_config.user_data[8],chip_ctrl.get_user_config.user_data[9],
        // chip_ctrl.get_user_config.user_data[10],chip_ctrl.get_user_config.user_data[11],chip_ctrl.get_user_config.user_data[12],chip_ctrl.get_user_config.user_data[13],
        // chip_ctrl.get_user_config.user_data[14],chip_ctrl.get_user_config.user_data[15]);
    }else{
        printf("un support cmd:%s! \n", ts->type);
    }
 
    return ret;
}

int SystemRequest(NetworkSystem* sys) {
    printf("system request type:%d\n", sys->type);
    if (sys->type == NETWORK_SYSTEM_DEVICE_INFO) {
        snprintf(sys->out.device_info.soft_version, sizeof(sys->out.device_info.soft_version), "V01.10");
        snprintf(sys->out.device_info.hard_version, sizeof(sys->out.device_info.hard_version), "V00.01");
        snprintf(sys->out.device_info.serial_number, sizeof(sys->out.device_info.serial_number), "1357924680");
    } else if (sys->type == NETWORK_SYSTEM_GET_RTSP_URL) {
        if(get_rtspurl_from_ini(sys->out.rtsp_url.main_stream) != 0){
            snprintf(sys->out.rtsp_url.main_stream, sizeof(sys->out.rtsp_url.main_stream), "rtsp://192.168.100.178/mainstream");
        }
    }else if(sys->type == NETWORK_SYSTEM_REBOOT){    
        pthread_t thread_id;
        if(pthread_create(&thread_id, NULL, delay_reboot, NULL ) != 0){
            perror("Create delay_reboot pthread failed!\n");
            return -1;
        }
    }else if(sys->type == NETWORK_SYSTEM_GET_TIME){
        long int cur_timestamp = -1;
        cur_timestamp = get_time_from_device();
        printf("get time is %ld\n", cur_timestamp);
        sys->out.cur_time= cur_timestamp;

    }else if(sys->type == NETWORK_SYSTEM_SET_TIME){
        int ret = -1;
        printf("set_time:%d\n",sys->in.time);
        char time_buf[16] = {0};
        sprintf(time_buf, "%d", sys->in.time);
        printf("set_time_s:%s\n",time_buf);
        ret = set_time_by_manaual(time_buf);
        rtc_init_systime_to_rtc();
        printf("timestamp test cmd!\n");
    }
    // else if(sys->type == NETWORK_SYSTEM_MEM_INFO){
    //     double cpu_usage = get_cpu_usage();
    //     double mem_usage = get_memory_usage();
    //     printf("cpu_usage-> %.2f, mem_usage: %.2f\n", cpu_usage, mem_usage);

    //     if(cpu_usage < 1){
    //         cpu_usage = 1.00;
    //     }
    //     sys->out.device_mem_info.cpu_useage = roundf(cpu_usage * 100) / 100.0f;
    //     sys->out.device_mem_info.mem_useage = roundf(mem_usage * 100) / 100.0f;

    //     printf("cpu_usage-> %f, mem_usage: %f\n", sys->out.device_mem_info.cpu_useage, sys->out.device_mem_info.mem_useage);
    // }
    return 0;
}


int device_init(NetworkCameraChipInfo *get_chip_ctrl){

    get_chip_ctrl->get_user_config.size = sizeof(get_chip_ctrl->get_user_config.user_data);
    printf("device_init size:%d!\n", get_chip_ctrl->get_user_config.size);
    int ret = chip_ctrl_init(DEVICE, CHIP_CRTL_GET_USER_CONFIG, get_chip_ctrl);
    if(ret  < 0){
        printf("device_init failed!\n");
        return -1;
    }
    // printf("解析结果: ");
    // for (int i = 0; i < get_chip_ctrl->get_user_config.size; i++) {
    //     printf("0x%02X ", get_chip_ctrl->get_user_config.user_data[i]);
    // }
    // printf("\n");
    //数据解析
    //1.极性,暂时不匹配
    int tmp_pseudo_color = -1;
    tmp_pseudo_color = get_chip_ctrl->get_user_config.user_data[0] & 0xf;
    if(tmp_pseudo_color == 2)
    {
        get_chip_ctrl->pseudo_color = 8;
    }else if(tmp_pseudo_color == 3){
        get_chip_ctrl->pseudo_color  = 2;
    }else{
        get_chip_ctrl->pseudo_color = tmp_pseudo_color;
    }
   
    //2.电子变倍
    get_chip_ctrl->electronic_zoom  = (get_chip_ctrl->get_user_config.user_data[2] * 256 + get_chip_ctrl->get_user_config.user_data[1]) / 1024;
    //3.快门校正开关
    get_chip_ctrl->shutter_calibration  = get_chip_ctrl->get_user_config.user_data[3] & 0x01;
    //5.水平翻转
    get_chip_ctrl->horizontal_image_flip    = get_chip_ctrl->get_user_config.user_data[4] & 0x01;
    //6.垂直翻转
    get_chip_ctrl->vertical_image_flip  =  get_chip_ctrl->get_user_config.user_data[5] & 0x01;
    //7.模拟视频开关
    get_chip_ctrl->analog_video_switch  = get_chip_ctrl->get_user_config.user_data[6] & 0x01;
    //8.模拟视频格式
    get_chip_ctrl->output_video_format  = get_chip_ctrl->get_user_config.user_data[7] & 0x01;

    int index = 0;
    for(index = CHIP_CRTL_PSEUDO_COLOR; index <= CHIP_CRTL_OUTPUT_VIDEO_FORMAT ; ++index){
        if(index == CHIP_CRTL_MANUAL_SHUTTER_CALIBRATION){
            continue;
        }

        ret = chip_ctrl_init(DEVICE , index, get_chip_ctrl); 
        if(0 > ret){
            printf("index=%d,exce failed!n", index);
            continue;
        }
    }

    return 0;
}

int set_osd_info(NetworkConfigOsdInfo *osd_dev_info){
    //字体
    osd_info.nFontInt = osd_dev_info->osd_attribute.size;
    int fontSize = osd_info.nFontInt;
    switch (fontSize)
    {
    case 0:
        osd_info.nOsdFontW = 12;
        osd_info.nOsdFontH = 12;
        break;
    case 1:
        osd_info.nOsdFontW = 16;
        osd_info.nOsdFontH = 16;
        break;
    case 2:
        osd_info.nOsdFontW = 24;
        osd_info.nOsdFontH = 24;
        break;
    case 3:
        osd_info.nOsdFontW = 32;
        osd_info.nOsdFontH = 32;
        break;
    default:
        osd_info.nOsdFontW = 24;
        osd_info.nOsdFontH = 24;
        break;
    }

    //颜色
    char *endptr;                    // 用于检查转换是否成功
    unsigned long hex_value;         // 存储转换后的十六进制数值
    hex_value = strtoul(osd_dev_info->osd_attribute.color + 1, &endptr, 16);
    long hex_num = strtol(osd_dev_info->osd_attribute.color + 1, &endptr, 16); // 16表示16进制

    printf("fontSize:%d, color is [%s]->0x%06x,[%x]\n",fontSize, osd_dev_info->osd_attribute.color,hex_value, hex_num);
    osd_color.rgbRed   = (hex_value >> 16) & 0xff;
    osd_color.rgbGreen  = (hex_value >> 8) & 0xff;
    osd_color.rgbBlue   = hex_value & 0xff;;
    pvideo_osd_status->nOsdColor = 5;

    printf("r:%02x, g:%02x, b:%02x\n", osd_color.rgbRed, osd_color.rgbGreen, osd_color.rgbBlue);
    //时间日期，坐标
    pvideo_osd_status->stDateOSD.Show = osd_dev_info->show_date;
    pvideo_osd_status->stWeekOSD.Show = osd_dev_info->show_week ;
    osd_pos.nOrgX = osd_dev_info->date_pos.x;
    osd_pos.nOrgY = osd_dev_info->date_pos.y;
    HH_OSD_ChnColor_Refresh(0);
    HH_OSD_ChnOrg_Refresh(0);

    return 0;
}

void* set_osd_default_info(void* arg){

    NetworkConfigOsdInfo *osd_dev_info = (NetworkConfigOsdInfo *)arg;
    while(1){
        usleep(1000);
        if(init_osd_flag == 1 ){
            printf("recv init over, exit!\n");
            load_osd_info_from_ini(osd_dev_info);
            set_osd_info(osd_dev_info);
            init_osd_flag = 0;
            break;
        }
    }
}

int main(int argc, char** argv) {
    
    NetworkCameraChipInfo get_chip_ctrl;
    memset(&get_chip_ctrl, 0x0, sizeof(get_chip_ctrl));
    NetworkInitialInfo net_init_info;
    memset(&net_init_info, 0x0, sizeof(net_init_info));
    //1.init net
    NetworkInit(&net_init_info);
    //2.init device info
    get_chipctrl_from_ini(&get_chip_ctrl);
    device_init(&get_chip_ctrl);
    //3.init rtc
    rtc_init_rtctime_to_sys();
    //4.init osd
    NetworkConfigOsdInfo osd_dev_info;
    memset(&osd_dev_info, 0x0, sizeof(osd_dev_info));
    // memcpy(&state.CaptureInfo, &get_snap_info, sizeof(NetworkConfigStorageSnapParam));获取抓拍默认配置赋值段错误

    NetworkOperationRegister(NETWORK_OPERATION_GET_ABILITY, GetAbility);
    NetworkOperationRegister(NETWORK_OPERATION_SYSTEM_REQUEST, SystemRequest);
    NetworkOperationRegister(NETWORK_OPERATION_GET_CONFIG, GetConfig);
    NetworkOperationRegister(NETWORK_OPERATION_SET_CONFIG, SetConfig);
    NetworkOperationRegister(NETWORK_OPERATION_CONTORL_REQUEST, ControlRequest);
    NetworkOperationRegister(NETWORK_OPERATION_UPGRADE, Upgrade);
    NetworkOperationRegister(NETWORK_OPERATION_TRANSPARENT_TRANSMISSION, TransparentTransmission);

    pthread_t init_osd = 0;
    pthread_create(&init_osd , 0, set_osd_default_info,  (void *)&osd_dev_info);
    
    main_app();
}